package com.mk.settlement.service.impl;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.mk.settlement.common.IPUtil;
import com.mk.settlement.mappers.SettlementSchedulerCenterMapper;
import com.mk.settlement.service.SchedulerService;

@Service("schedulerService")
public class SchedulerServiceImpl implements SchedulerService {

    private Logger log = LoggerFactory.getLogger(SchedulerServiceImpl.class);

    @Resource
    private SettlementSchedulerCenterMapper SettlementSchedulerCenterMapper;

    private final static String LOCALIP = IPUtil.getLocalIPV4();

    private static final String ERRORLOCALIP = "127.0.0.1";

    // 是否取得执行权限,默认false
    private boolean havePermission = false;

    @PostConstruct
    private void printLocalIP() {

        log.info("本机IP:" + LOCALIP);
    }

    @Override
    public boolean havePermission(String taskName) {

        if (LOCALIP == null || LOCALIP.equals(ERRORLOCALIP)) {

            log.error("定时任务[" + taskName + "]获取到的本机ip为:" + LOCALIP + ",本轮不执行.");
        }

        boolean canRun = false;

        try {
            int result = SettlementSchedulerCenterMapper.updateScheduler(taskName, LOCALIP);

            canRun = result > 0 ? true : false;

            if (canRun != havePermission) {

                // 原来是有执行权限的
                if (havePermission) {
                    log.info(LOCALIP + "失去定时任务[" + taskName + "]执行权限,请验证.");
                }

                havePermission = canRun;
            }
            
            if(havePermission) {
                log.info(LOCALIP + "获得定时任务[" + taskName + "]执行权限,请验证.");
            }

        } catch (Exception e) {
            log.error("定时任务[" + taskName + "]获取执行权限时异常!", e);

            return false;
        }
        
        return havePermission;
    }

}
